﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace ChatServerApplication
{

    class Serverhandling
    {
        private Socket sock;

        public Serverhandling(Socket sock) { this.sock = sock; }

        public void Run()
        {
            String request = getContent();
            try
            {
                String[] lines = request.Split(Environment.NewLine.ToCharArray());
                String[] words = lines[0].Split(" ".ToCharArray());
                if (words[0] == "GET")
                {
                    int pos = words[1].LastIndexOf("/");
                    if (pos > -1)
                    {
                        if (words[1] != "/" && words[1].Length > pos)
                        {
                            String filename = words[1].Substring(pos + 1);
                            if (File.Exists(Application.StartupPath + "\\files\\" + filename))
                            {
                                sendFile(filename);
                            }
                            else
                            {
                                sendResponse("404 NOT FOUND", "Datei nicht gefunden");
                            }
                        }
                        else
                        {
                            if (File.Exists(Application.StartupPath + "\\files\\index.html"))
                                sendFile("index.html");
                            else
                                sendResponse("200 OK", "Index");
                        }
                    }
                    else
                    {
                        sendResponse("400 BAD REQUEST", "Protokollfehler");
                    }
                }
                else
                {
                    sendResponse("400 BAD REQUEST", "Nicht unterstützt");
                }
            }
            catch
            {
                sendResponse("400 BAD REQUEST", "Protokollfehler");
            }
            sock.Close();
        }

        private void sendResponse(String status, String tosend)
        {
            LogConsole(status);
            sendText("HTTP/1.1 " + status);
            sendText("Server: CLWebserver 1.00");
            sendText("Connection: close");
            sendText("Content-Type: text/html");
            sendText("Content-Length: " + (tosend.Length + Environment.NewLine.Length));
            sendText("");
            sendText(tosend);
        }

        private void sendText(String text)
        {
            sock.Send(Encoding.UTF8.GetBytes(text + Environment.NewLine));
        }

        private void sendFile(String filename)
        {
            FileStream stream = new FileStream(Application.StartupPath + "\\files\\" + filename, FileMode.Open);
            LogConsole("200 OK [ " + filename + " ]");
            sendText("HTTP/1.1 200 OK");
            sendText("Server: CLWebserver 1.00");
            sendText("Connection: close");
            sendText("Content-Type: text/html");
            sendText("Content-Length: " + stream.Length);
            sendText("");
            long read = 0;
            while (read < stream.Length)
            {
                int buffersize;
                if (stream.Length - read > 1024)
                {
                    buffersize = 1024;
                    read += 1024;
                }
                else
                {
                    buffersize = (int)(stream.Length - read);
                    read = stream.Length;
                }
                byte[] tosend = new byte[buffersize];
                stream.Read(tosend, 0, buffersize);
                sock.Send(tosend);
                Thread.Sleep(1);
            }
            stream.Close();
        }

        private String getContent()
        {
            String content = "";
            Thread.Sleep(10);
            while (sock.Available > 0)
            {
                int bytes = sock.Available;
                byte[] buffer = new byte[bytes];
                sock.Receive(buffer, bytes, SocketFlags.None);
                content += Encoding.UTF8.GetString(buffer);
                Thread.Sleep(10);
            }
            return content;
        }

        private void LogConsole(String Message)
        {
            Console.WriteLine(((IPEndPoint)sock.RemoteEndPoint).Address.ToString() + " - " + Message);
        }

    }

}
